Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

401
Visualizações
Change background-color of div when "radio" is selected

I need to change the background-color of the parent div of a input (radio type) when the input is selected, but, if the user selects another input, the original div needs to go back to it's original color, and change the div of the newly selected input. So far, i only made a function that changes the div color depending on the selected input, so if i click on another input, both divs will have their color changed. I searched for a solution for this, but couldn't find any.. The code is this so far:

function changeBg(posicao) {
  var changer = document.getElementById(posicao);
  if (changer.checked = true) {
    changer.style.backgroundColor = "#FFCE00";
  }
}
<div class="posicao" id="um">
  <input class="input-posicao " onclick="changeBg('um')" name="posicao" value="um" type="radio">
</div>

<div class="posicao" id="dois">
  <input class="input-posicao " onclick="changeBg('dois')" name="posicao" value="dois" type="radio">
</div>

<div class="posicao">
  <input class="input-posicao" onclick="changeBg('tres')" name="posicao" value="tres" type="radio">
</div>

<div class="posicao">
  <input class="input-posicao" onclick="changeBg('quatro')" name="posicao" value="quatro" type="radio">
</div>

<div class="posicao">
  <input class="input-posicao" onclick="changeBg('cinco')" name="posicao" value="cinco" type="radio">
</div>

<div class="posicao">
  <input class="input-posicao" onclick="changeBg('seis')" name="posicao" value="seis" type="radio">
</div>

<div class="posicao">
  <input class="input-posicao" onclick="changeBg('sete')" name="posicao" value="sete" type="radio">
</div>

<div class="posicao">
  <input class="input-posicao" onclick="changeBg('oito')" name="posicao" value="oito" type="radio">
</div>

<div class="posicao">
  <input class="input-posicao" onclick="changeBg('nove')" name="posicao" value="nove" type="radio">
</div>

In the print, you can see what happens if i select 2 inputs..

enter image description here

about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

You don't need to attach an event listener to each radio button. Just create a wrapper around each and listen for the change event there (Event Delegation).

And the styling can be done through css with e.g. an active class. The active can be removed from the previously active element. And then added to the currently active one.

document.querySelector('.radiogroup').addEventListener('change', (evt) => {
  // evt.currentTarget is the .radiogroup element
  // and we search for all elements with the active class
  evt.currentTarget
    .querySelectorAll('.active')
    .forEach(element => {
      // remove the active class from those elements
      element.classList.remove('active')
    })
  
  
  // in this simple case evt.target is the radio button 
  // that became active for more complex event delegation you
  // need to check what evt.target is.
  // search for the ascendant with the class posicao
  // and add the active class to it
  evt.target
    .closest('.posicao')
    .classList.add('active');
}, true);
.posicao {
  display: inline-block;
  background: grey;
}

.active {
  background-color: yellow;
}
<div class="radiogroup">
  <div class="posicao">
    <input name="posicao" type="radio">
  </div>
  <div class="posicao">
    <input name="posicao" type="radio">
  </div>
  <div class="posicao">
    <input name="posicao" type="radio">
  </div>
  <div class="posicao">
    <input name="posicao" type="radio">
  </div>
  <div class="posicao">
    <input name="posicao" type="radio">
  </div>
</div>

about 4 years ago · Santiago Gelvez Relatório

0

First of all its not a good practice to call functions inline in the html file, add an event listener in you script and handle user inputs there:

const radios = document.querySelectorAll('input[type="radio"]');
radios.forEach(radio => {
   radio.onclick = () => {
      radios.forEach(radio => {
         radio.style.backgroundColor = radio.checked ? '#FFCE00' : '#ffffff';
      });
   }
});
about 4 years ago · Santiago Gelvez Relatório

0

Here you are a working vanilla js function for your prob.

But You have missed id from sencond 'posicao' div to last, add the correct id.

function changeBg(id) {
        let changer = document.getElementById(id);
        let all = document.getElementsByClassName('posicao');
        console.log(all);
          for (let i =0; i<all.length; i++){
              all[i].classList.remove('color')
          }
        changer.classList.add("color");
        
    }
</script>
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda